/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;
import com.google.zxing.camera.CameraManager;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.preview.QrCodeForegroundPreview;

import java.io.IOException;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

/**
 * This activity opens the camera and does the actual scanning on a background thread. It draws a
 * viewfinder to help the user place the barcode correctly, shows feedback as the image processing
 * is happening, and then overlays the results when a scan is successful.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class QrCodeCameraPreviewActivity extends SwipeBackBaseActivity implements SurfaceHolder.Callback {

    private static final String TAG = QrCodeCameraPreviewActivity.class.getSimpleName();

    private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
    private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;

    public static final String IS_FROM_LIGHTAPP = "is_from_lightapp";//从轻应用跳转过来
    public static final String INTENT_IS_FROM_TYPE_KEY = "intent_is_from_type_key";//从其他界面过来传的标识类型的key
    private String isFromType;//从其他界面过来的标识类型
    private int mJudgeTaskId = -1;
    private ImageView iv_qrcode_light_open;
    private boolean isOpenFlashlight;
    private TextView tv_qrcode_light_text;

    private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
            EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
                    ResultMetadataType.SUGGESTED_PRICE,
                    ResultMetadataType.ERROR_CORRECTION_LEVEL,
                    ResultMetadataType.POSSIBLE_COUNTRY);

    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private Result savedResultToShow;
    private QrCodeForegroundPreview viewfinderView;

    private Result lastResult;
    private boolean hasSurface;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet = "utf-8";
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private AmbientLightManager ambientLightManager;
    private ImageView ivScanView;

    QrCodeForegroundPreview getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    CameraManager getCameraManager() {
        return cameraManager;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.qr_code_scan);
        initDatas();
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        ambientLightManager = new AmbientLightManager(this);
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    private void initDatas() {
        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        if (data != null) {
            isFromType = data.getString(INTENT_IS_FROM_TYPE_KEY);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
        // want to open the camera driver and measure the screen size if we're going to show the help on
        // first launch. That led to bugs where the scanning rectangle was the wrong size and partially
        // off screen.
        cameraManager = new CameraManager(getApplication());
        viewfinderView = (QrCodeForegroundPreview) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        initView();

        handler = null;
        lastResult = null;

        setCurrentOrientation();

        beepManager.updatePrefs();
        ambientLightManager.start(cameraManager);

        inactivityTimer.onResume();

        decodeFormats = null;
        characterSet = null;

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            // The activity was paused but not stopped, so the surface still exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(surfaceHolder);
        } else {
            // Install the callback and wait for surfaceCreated() to init the camera.
            surfaceHolder.addCallback(this);
        }
    }

    public void initView() {
        ivScanView = (ImageView) findViewById(R.id.iv_scan_bar);
        viewfinderView = (QrCodeForegroundPreview) findViewById(R.id.viewfinder_view);
        iv_qrcode_light_open = (ImageView) findViewById(R.id.iv_qrcode_light_open);
        tv_qrcode_light_text = (TextView) findViewById(R.id.tv_qrcode_light_text);
        iv_qrcode_light_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doOpenFlashlight(!isOpenFlashlight);
            }
        });
        findViewById(R.id.text_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void initBarLineAmimator() {
        Rect frame = cameraManager.getFramingRect();
        if (frame == null) {
            ivScanView.setVisibility(View.GONE);
            return;
        }
        ivScanView.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ivScanView.getLayoutParams();
        int padding = 6;
        float duration = frame.bottom - frame.top - 2 * padding;
        layoutParams.setMargins(layoutParams.leftMargin, frame.top, layoutParams.rightMargin, layoutParams.bottomMargin);
        ivScanView.setLayoutParams(layoutParams);

        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(ivScanView, "translationY", 0.0f, duration);
        objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        objectAnimator.setRepeatCount(-1);
        objectAnimator.setRepeatMode(ValueAnimator.RESTART);
        objectAnimator.setDuration(3000);
        objectAnimator.start();
    }


    /**
     * 打开或者关闭上闪光灯
     *
     * @param open
     */
    private void doOpenFlashlight(boolean open) {
        try {
            if (open) {
                iv_qrcode_light_open.setImageResource(R.drawable.qrcode_scan_light_close);
                tv_qrcode_light_text.setText(getResources().getString(R.string.qrcode_scan_light_close));
            } else {
                iv_qrcode_light_open.setImageResource(R.drawable.qrcode_scan_light_open);
                tv_qrcode_light_text.setText(getResources().getString(R.string.qrcode_scan_light_open));
            }
            cameraManager.setTorch(open);
            isOpenFlashlight = open;
        } catch (Exception e) {
            showToast(R.string.qrcode_scan_open_flashlight_error);
        }
    }

    private void setCurrentOrientation() {
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            switch (rotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_90:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                default:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }
        } else {
            switch (rotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_270:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                default:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            }
        }
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        ambientLightManager.stop();
        beepManager.close();
        cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
        // Bitmap isn't used yet -- will be used soon
        if (handler == null) {
            savedResultToShow = result;
        } else {
            if (result != null) {
                savedResultToShow = result;
            }
            if (savedResultToShow != null) {
                Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
                handler.sendMessage(message);
            }
            savedResultToShow = null;
        }
    }

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!hasSurface) {
            hasSurface = true;
            checkPermission(PermissionUtil.PERMISSION_CAMERA_SCAN, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, List<String> grantedList) {
                    initCamera(holder);
                }

                @Override
                public void onFailed(int requestCode, List<String> deniedList) {

                }
            }, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * A valid barcode has been found, so give an indication of success and show the results.
     *
     * @param rawResult The contents of the barcode.
     */
    public void handleDecode(Result rawResult) {
        inactivityTimer.onActivity();
        lastResult = rawResult;
        ParsedResult result = ResultParser.parseResult(rawResult);

        boolean fromLiveScan = rawResult != null;
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();
        }
        String resultStr = rawResult.getText();
//        showToast(resultStr);
//        restartPreviewAfterDelay(3);
        if (TextUtils.isEmpty(resultStr)) {
            restartPreviewAfterDelay(3000);
        } else {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("result", resultStr);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            finish();
        }

    }

    // Put up our own UI for how to handle the decoded contents.
    private void handleDecodeInternally(Result rawResult) {

        CharSequence displayContents = rawResult.getText();

        viewfinderView.setVisibility(View.GONE);

        Log.i(TAG, "format: " + rawResult.getBarcodeFormat().toString());
//    Log.i(TAG, "type: " + result.getType().toString());


        Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata();
        if (metadata != null) {
            StringBuilder metadataText = new StringBuilder(20);
            for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) {
                if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
                    metadataText.append(entry.getValue()).append('\n');
                }
            }
            if (metadataText.length() > 0) {
                metadataText.setLength(metadataText.length() - 1);
                Log.i(TAG, "metadata: " + metadataText);
            }
        }

        Log.i(TAG, "content: " + displayContents);

    }

    private void sendReplyMessage(int id, Object arg, long delayMS) {
        if (handler != null) {
            Message message = Message.obtain(handler, id, arg);
            if (delayMS > 0L) {
                handler.sendMessageDelayed(message, delayMS);
            } else {
                handler.sendMessage(message);
            }
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
            }
            decodeOrStoreSavedBitmap(null, null);
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }

        //下面方法依赖于initCamera()的实例化
        initBarLineAmimator();
    }

    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage(getString(R.string.msg_camera_framework_bug));
        builder.setPositiveButton(R.string.sure, new FinishListener(this));
        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
        lastResult = null;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }
}
